package com.turtledove.storyalbum.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.turtledove.storyalbum.R;
import com.turtledove.storyalbum.common.ConstCommon;
import com.turtledove.storyalbum.common.UtilsCommon;
import com.turtledove.storyalbum.model.adapter.AdapterInstagramUpdate;
import com.turtledove.storyalbum.model.delegate.ServiceDelegate;
import com.turtledove.storyalbum.model.delegate.instagramplugin.ApplicationData;
import com.turtledove.storyalbum.model.delegate.instagramplugin.InstagramApp;
import com.turtledove.storyalbum.model.delegate.instagramplugin.InstagramApp.OAuthAuthenticationListener;
import com.turtledove.storyalbum.model.helper.DBHandler;
import com.turtledove.storyalbum.model.object.ObjectImage;
import com.turtledove.storyalbum.model.object.ObjectInstagramImage;

public class InstagramUpdateActivity  extends Activity implements OnClickListener {

	GridView gridContent;
	AdapterInstagramUpdate adapter;
	TextView txtItemSelected, txtDone;
	ArrayList<ObjectInstagramImage> arrayImage, arrayImageSelected;
	ArrayList<ObjectImage> arrayImageClient;
	Dialog dialog;//, dialogDownload;
	Context mContext;
	int idAlbum;
	String access_token;
	String urlFolder;
	ViewFlipper vf;
	int LOADING = 0, CONTENT = 1, ERRO = 2;
	private InstagramApp mApp;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_instagram);
		initDB();
		initWidget();
		loginInstagram();
	}

	void initDB()
	{
		mContext = this;
		Intent intent = new Intent();
		intent = getIntent();
		idAlbum = intent.getExtras().getInt(ConstCommon.KEY_FROM_WHERE_ITEM_ID_ALBUM);
	}
	
	private void initWidget() {
		vf = (ViewFlipper) findViewById(R.id.vf);
		vf.setDisplayedChild(LOADING);
		arrayImage = new ArrayList<ObjectInstagramImage>();
		arrayImageClient = new ArrayList<ObjectImage>();
		mContext = this;
		txtItemSelected = (TextView) findViewById(R.id.txtItemSelected);
		txtItemSelected.setOnClickListener(this);
		txtDone = (TextView) findViewById(R.id.txtDone);
		txtDone.setOnClickListener(this);
	}
	
	void loginInstagram()
	{
		try {
			mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
					ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
			mApp.setListener(listener);
			if (mApp.hasAccessToken() == false) {
				mApp.authorize();
			} 
			if (mApp.hasAccessToken()) {
				access_token = mApp.getStrAccessToken();
				setDB();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	
	
	OAuthAuthenticationListener listener = new OAuthAuthenticationListener() {

		@Override
		public void onSuccess() {
		}

		@Override
		public void onFail(String error) {
			loginInstagram();
		}
	};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.txtDone:
			showDialogInstagram();

			break;

		default:
			break;
		}
	}
	
	void setDB()
	{
		ServiceDelegate.getInstagramImage(mhandlerImage, access_token);
	}
	
	private void showDialogInstagram() {
		try {
			if (idAlbum > 0) {
				arrayImageSelected = getListImageSelected();
				if (arrayImageSelected.size() > 0) {
					arrayImageClient = new ArrayList<ObjectImage>();
					downloadFile(idAlbum);
					// change status service widget
					WidgetUpdateService.statusCurrentAlbum = true;
					updateListImage(idAlbum);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

		// download file
		public void downloadFile(final int maxIdAlbum) {
			try {
//				dialogDownload = ProgressDialog.show(this, "", getString(R.string.downloading_file),
//						true);
						final String urlFolder = UtilsCommon.createFolder(getString(R.string.instagram));
						new Thread(new Runnable() {
						 public void run() {
								 for(int i=0; i< arrayImageSelected.size(); i++)
								 {
									 ObjectInstagramImage mObjectInstagramImage = arrayImageSelected.get(i);
									 String urlDownload = mObjectInstagramImage.getImage_source();
									 boolean checkStatus = UtilsCommon.downLoadFile(InstagramUpdateActivity.this, urlDownload, urlFolder);
									 if(checkStatus != false)
									 {
										 Log.d("Luong", "************************ download image: "+mObjectInstagramImage.getImage_source());
										 String itemCover = "0";
											if (i == 0) {
												itemCover = "1";
											}
										ObjectImage mObjectImage = new ObjectImage();
										mObjectImage.setUrlImage(urlFolder+"/"+urlDownload.substring(urlDownload.lastIndexOf("/")));
										arrayImageClient.add(mObjectImage);
										 DBHandler.insertItem(mContext, mObjectImage.getUrlImage(), String.valueOf(maxIdAlbum), itemCover);
									 }else{
										 Log.e("Luong", "************************ download image fail: "+mObjectInstagramImage.getImage_source());
									 }
								 }
//								 dialogDownload.dismiss();
							 }
						}).start();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	
	
	public ArrayList<ObjectInstagramImage> getListImageSelected() {
		ArrayList<ObjectInstagramImage> listImageSelected = new ArrayList<ObjectInstagramImage>();
		try {
			if (arrayImage.size() > 0) {
				for (int i = 0; i < arrayImage.size(); i++) {
					if (arrayImage.get(i).isSelected()) {
						listImageSelected.add(arrayImage.get(i));
					}
				}
			}
			txtItemSelected.setText(listImageSelected.size() + " "
					+ getResources().getString(R.string.selected));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listImageSelected;
	}
	
	void updateListImage(int idAlbum) {
		Intent returnIntent = new Intent();
		returnIntent.putExtra(ConstCommon.KEY_RESULT_ID_ALBUM, idAlbum);
		setResult(RESULT_OK, returnIntent);
		finish();
	}
	
	Handler mhandlerImage = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					JSONArray dataJSONArray = new JSONArray();
					dataJSONArray = dataJSONObject
							.getJSONArray(ServiceDelegate.KEY_DATA);
					Log.d("Luong","Luong_____________________________ dataJSONArray: "+ dataJSONArray);
					int totalImage = dataJSONArray.length();
					if (totalImage > 0) {
						
						arrayImage = new ArrayList<ObjectInstagramImage>();
						
						for (int i = 0; i < totalImage; i++) {
							JSONObject itemJSONObject = new JSONObject();
							itemJSONObject = dataJSONArray.getJSONObject(i);

							JSONObject imageJSONObject = new JSONObject();
							imageJSONObject = itemJSONObject.getJSONObject(ServiceDelegate.KEY_IMAGE);
							
							JSONObject low_resolutionJSONObject = new JSONObject();
							low_resolutionJSONObject = imageJSONObject.getJSONObject(ServiceDelegate.KEY_LOW_RESOLUTION);
							
							ObjectInstagramImage mObjectInstagramImage = new ObjectInstagramImage();
							mObjectInstagramImage.setImage_source(low_resolutionJSONObject.getString(ServiceDelegate.KEY_URL));
							mObjectInstagramImage.setImage_height((float) low_resolutionJSONObject.getDouble(ServiceDelegate.KEY_HEIGHT));
							mObjectInstagramImage.setImage_width((float) low_resolutionJSONObject.getDouble(ServiceDelegate.KEY_WIDTH));
							
							arrayImage.add(mObjectInstagramImage);
						}
						if (arrayImage.size() > 0) {
							Log.d("Luong", "Luong_______________________ total img: "+arrayImage.size());
							vf.setDisplayedChild(CONTENT);
							adapter = new AdapterInstagramUpdate(InstagramUpdateActivity.this, arrayImage);
							gridContent = (GridView) findViewById(R.id.gridContent);
							gridContent.setFastScrollEnabled(true);
							gridContent.setAdapter(adapter);
						}else{
							vf.setDisplayedChild(ERRO);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	};
}
